package ink.xiaobaibai.controller.free;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ink.xiaobaibai.autoConfig.roleResources.ResourcesRoleMapping;
import ink.xiaobaibai.common.FreeDeviceStatus;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.common.SelectFreeDeviceBo;
import ink.xiaobaibai.entity.FreeOxygenDevice;
import ink.xiaobaibai.entity.FreeOzoneDevice;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IAdminUserService;
import ink.xiaobaibai.service.IFreeOxygenDeviceService;
import ink.xiaobaibai.service.IFreeOzoneDeviceService;
import ink.xiaobaibai.units.MySecurity;
import ink.xiaobaibai.valited.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 免费机器臭氧机控制层
 * @author: 小白白
 * @create: 2021-07-20
 **/

@RestController
@RequestMapping("/free/ozone")
@Api(tags = "免费臭氧机器接口")
@CrossOrigin
public class FreeOzoneDeviceController {

    @Autowired
    private IFreeOzoneDeviceService freeOzoneDeviceService;

    @Autowired
    private IFreeOxygenDeviceService freeOxygenDeviceService;

    @Autowired
    private IAdminUserService adminUserService;

    /**
     * 查询
     */
    @PostMapping("/list")
    @ApiOperation("查询自己的臭氧机")
    public ResponseFormat list(@RequestBody @Validated SelectFreeDeviceBo selectFreeDeviceBo) {
        Integer userId = MySecurity.getUserId();
        QueryWrapper<FreeOzoneDevice> q1 = new QueryWrapper<>();
        if (!MySecurity.isPower(MyRole.POWER_FREE)) {
            String role = MySecurity.getRole();
            if (role.equals(MyRole.DISTRIBUTOR) && !MySecurity.getRoles().contains(MyRole.POWER_FREE)) {
                q1.eq("admin_user_id", userId);
            }
            if (role.equals(MyRole.AGENT) && !MySecurity.getRoles().contains(MyRole.POWER_FREE)) {
                q1.eq("dep_id", this.adminUserService.getDepId(userId));
            }
        }
        if (selectFreeDeviceBo.getAdminUserId() != null) {
            q1.eq("admin_user_id", selectFreeDeviceBo.getAdminUserId());
        }
        if (selectFreeDeviceBo.getAddress() != null) {
            q1.likeRight("address", selectFreeDeviceBo.getAddress());
        }
        if (selectFreeDeviceBo.getProvinceCity() != null) {
            q1.eq("province_city", selectFreeDeviceBo.getProvinceCity());
        }
        Page<FreeOzoneDevice> page = this.freeOzoneDeviceService.page(new Page<>(selectFreeDeviceBo.getPageNum(), selectFreeDeviceBo.getPageSize()), q1);
        return ResponseFormat.success(page);
    }

    /**
     * 增加
     */
    @PostMapping("/add")
    @ApiOperation("增加免费臭氧机")
    @ResourcesRoleMapping(resourceName = "增加免费臭氧机", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_FREE})
    public ResponseFormat addOzoneDevice(@RequestBody @Validated FreeOzoneDevice freeOzoneDevice) {
        Integer oxygenId = freeOzoneDevice.getOxygenId();
        QueryWrapper<FreeOxygenDevice> q1 = new QueryWrapper<>();
        q1.eq("id", freeOzoneDevice.getOxygenId());
        if (this.freeOxygenDeviceService.count(q1) == 0) {
            return ResponseFormat.fail("请输入正确的氧气机id");
        }
        Integer userId = MySecurity.getUserId();
        if (this.existDeviceCode(freeOzoneDevice.getDeviceCode())) {
            return ResponseFormat.fail("机器码重复");
        }

        if (freeOzoneDevice.getAdminUserId() == null) {
            freeOzoneDevice.setAdminUserId(userId);
            freeOzoneDevice.setDepId(this.adminUserService.getDepId(userId));
        } else {
            if (!this.adminUserService.existsUser(freeOzoneDevice.getAdminUserId())) {
                return ResponseFormat.fail("绑定用户不存在");
            }
            freeOzoneDevice.setDepId(this.adminUserService.getDepId(freeOzoneDevice.getAdminUserId()));
        }

        // 判断单个房间是否包含在所有房间内
        List<String> roomNumber = freeOzoneDevice.getRoomNumber();
        if (freeOzoneDevice.getSingleRoomNumber() != null) {
            for (String str : freeOzoneDevice.getSingleRoomNumber()) {
                if (!roomNumber.contains(str)) {
                    return ResponseFormat.fail(str + "单次房间号不包含在所有房间号内");
                }
            }
        }

        freeOzoneDevice.setOxygenId(oxygenId);
        freeOzoneDevice.setStatus(FreeDeviceStatus.FREE.getStatus());

        if (freeOzoneDevice.getSingleRoomNumber() == null) {
            freeOzoneDevice.setSingleRoomNumber(new ArrayList<>());
        }

        this.freeOzoneDeviceService.save(freeOzoneDevice);
        return ResponseFormat.success();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation("修改免费臭氧机")
    @ResourcesRoleMapping(resourceName = "修改免费臭氧机", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_FREE})
    public ResponseFormat updateOzoneDevice(@RequestBody @Validated(UpdateGroup.class) FreeOzoneDevice freeOzoneDevice) {
        Integer userId = MySecurity.getUserId();
        QueryWrapper<FreeOzoneDevice> q1 = new QueryWrapper<>();
        q1.select("admin_user_id", "device_code");
        q1.eq("id", freeOzoneDevice.getId());
        FreeOzoneDevice dbFreeOzoneDevice = this.freeOzoneDeviceService.getOne(q1);
        if (!freeOzoneDevice.getDeviceCode().equals(dbFreeOzoneDevice.getDeviceCode()) && this.existDeviceCode(freeOzoneDevice.getDeviceCode())) {
            return ResponseFormat.fail("机器码重复");
        }

        if (freeOzoneDevice.getAdminUserId() != null && !StringUtils.equals(String.valueOf(freeOzoneDevice.getAdminUserId()), String.valueOf(userId))) {
            if (!this.adminUserService.existsUser(freeOzoneDevice.getAdminUserId())) {
                return ResponseFormat.fail("绑定用户不存在");
            }
            freeOzoneDevice.setDepId(this.adminUserService.getDepId(freeOzoneDevice.getAdminUserId()));
        }

        // 判断单个房间是否包含在所有房间内
        List<String> roomNumber = freeOzoneDevice.getRoomNumber();
        if (freeOzoneDevice.getSingleRoomNumber() != null) {
            for (String str : freeOzoneDevice.getSingleRoomNumber()) {
                if (!roomNumber.contains(str)) {
                    return ResponseFormat.fail(str + "单次房间号不包含在所有房间号内");
                }
            }
        }

        this.freeOzoneDeviceService.updateById(freeOzoneDevice);
        return ResponseFormat.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除免费臭氧机器")
    @ResourcesRoleMapping(resourceName = "删除免费臭氧机", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_FREE})
    public ResponseFormat deleteFreeOzoneDevice(@PathVariable("id") Integer deviceId) {
        this.freeOzoneDeviceService.removeById(deviceId);
        return ResponseFormat.success();
    }

    // 机器码是否已经存在
    private boolean existDeviceCode(String deviceCode) {
        QueryWrapper<FreeOzoneDevice> q1 = new QueryWrapper<>();
        q1.eq("device_code", deviceCode);
        return this.freeOzoneDeviceService.count(q1) >= 1;
    }

}
